<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Stock Data Chart</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.2.2/echarts.min.js"></script>
</head>
<body>
<div id="main" style="width: 100%; height: 600px;"></div>
<input type="date" id="dateInput" placeholder="请输入日期">
<button id="searchBtn">查询</button>
<div id="result"></div>
<div id="dataContainer"></div>

<script>
// 初始化ECharts
var chart = echarts.init(document.getElementById('main'));

// 初始化数据为空数组
var stockData = [];

// 获取数据
function fetchData() {
    fetch("/stock_data")
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
        }
        return response.json();
    })
    .then(data => {
        // 更新全局的 stockData
        stockData = data;

        // 处理数据并设置图表
        const dates = stockData.map(item => item.date);
        const openPrices = stockData.map(item => item.open);
        const closePrices = stockData.map(item => item.close);
        const lowPrices = stockData.map(item => item.low);
        const highPrices = stockData.map(item => item.high);

        const option = {
            title: {
                text: 'Stock Candlestick Chart'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                },
                formatter: function(params) {
                    var item = params[0];
                    return [
                        'Date: ' + item.name,
                        'Open: ' + item.data[0],
                        'Close: ' + item.data[1],
                        'Lowest: ' + item.data[2],
                        'Highest: ' + item.data[3]
                    ].join('<br/>');
                }
            },
            xAxis: {
                type: 'category',
                data: dates,
                axisLabel: {
                    formatter: function (value) {
                        return new Date(value).toISOString().split('T')[0];
                    }
                },
                scale: true, // 开启数值轴刻度自动计算
                boundaryGap : false // 坐标轴两边留白策略，即数据最左侧和最右侧的点位于两条最左侧和最右侧刻度线上
            },
            yAxis: {
                type: 'value',
                scale: true,
                axisLabel: {
                    formatter: '{value}'
                }
            },
            dataZoom: [ // 数据区域缩放控制器
                {
                    type: 'inside', // 内置型数据区域缩放
                    start: 0, // 数据窗口范围的起始百分比
                    end: 100 // 数据窗口范围的结束百分比
                },
                {
                    start: 0,
                    end: 100,
                    handleSize: '80%', // 滑动条的手柄大小
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }
            ],
            series: [{
                name: 'Stock Data',
                type: 'candlestick',
                data: stockData.map(item => [item.open, item.close, item.low, item.high]),
                markPoint: {
                    symbol: 'pin',
                    data: [
                        {type: 'max', name: 'Highest'},
                        {type: 'min', name: 'Lowest'}
                    ]
                },
                markLine: {
                    symbol: ['none', 'none'],
                    data: [
                        {type: 'average', name: 'Average'}
                    ]
                }
            }]
        };

        chart.setOption(option);
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });
}

// 初次加载页面时获取数据
fetchData();

document.getElementById('searchBtn').addEventListener('click', function() {
    const date = document.getElementById('dateInput').value;
    if (date) {
        const selectedData = stockData.find(item => item.date.split('T')[0] === date);
        if (selectedData) {
            const resultDiv = document.getElementById('result');

            // 计算涨跌额的颜色
            let changeColor;
            if (selectedData.changeAmount > 0) {
                changeColor = 'red'; // 涨
            } else if (selectedData.changeAmount < 0) {
                changeColor = 'green'; // 跌
            } else {
                changeColor = 'black'; // 平
            }

            // 计算涨跌幅的颜色
            let changePercentageColor;
            if (selectedData.changePercentage > 0) {
                changePercentageColor = 'red'; // 涨
            } else if (selectedData.changePercentage < 0) {
                changePercentageColor = 'green'; // 跌
            } else {
                changePercentageColor = 'black'; // 平
            }

            // 计算收盘价的颜色
            let closeColor;
            if (selectedData.close > selectedData.open) {
                closeColor = 'red'; // 收盘价比开盘价高，红色
            } else if (selectedData.close < selectedData.open) {
                closeColor = 'green'; // 收盘价比开盘价低，绿色
            } else {
                closeColor = 'black'; // 收盘价等于开盘价，黑色（默认）
            }

            // 格式化并显示查询结果，涨跌额、涨跌幅和收盘价根据颜色显示
            resultDiv.innerHTML = `
                <div style="border: 1px solid #ccc; padding: 10px; margin-top: 10px;">
                    <h3>查询结果</h3>
                    <ul style="list-style-type: none; padding: 0;">
                        <li><strong>ID:</strong> ${selectedData.id}</li>
                        <li><strong>日期:</strong> ${selectedData.date.split('T')[0]}</li>
                        <li><strong>开盘价:</strong> ${selectedData.open}</li>
                        <li><strong>收盘价:</strong> <span style="color: ${closeColor};">${selectedData.close}</span></li>
                        <li><strong>最高价:</strong> ${selectedData.high}</li>
                        <li><strong>最低价:</strong> ${selectedData.low}</li>
                        <li><strong>成交量:</strong> ${selectedData.volume}</li>
                        <li><strong>交易金额:</strong> ${selectedData.transactionAmount}</li>
                        <li><strong>涨跌额:</strong> <span style="color: ${changeColor};">${selectedData.changeAmount}</span></li>
                        <li><strong>涨跌幅:</strong> <span style="color: ${changePercentageColor};">${selectedData.changePercentage}%</span></li>
                        <li><strong>振幅:</strong> ${selectedData.amplitude}</li>
                        <li><strong>换手率:</strong> ${selectedData.turnoverRate}</li>
                    </ul>
                </div>
            `;
        } else {
            const resultDiv = document.getElementById('result');
            resultDiv.innerHTML = `找不到日期为 ${date} 的数据`;
        }
    } else {
        alert('请输入日期');
    }
});

</script>
</body>
</html>
